using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.WriteApi.Appcontext.Command;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, bool>
	{
		private readonly IBaseRepository<Role> _roleRepo;
		private readonly IBaseRepository<RolePermission> _rpRepo;
		private readonly IBaseRepository<EmployeeRole> _erRepo;

		public DeleteRoleCommandHandler(IBaseRepository<Role> roleRepo, IBaseRepository<RolePermission> rpRepo, IBaseRepository<EmployeeRole> erRepo)
		{
			_roleRepo = roleRepo;
			_rpRepo = rpRepo;
			_erRepo = erRepo;
		}

		public async Task<bool> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
		{
			var role = await _roleRepo.GetModel(x => x.RoleId == request.RoleId);
			if (role == null) throw new Exception("角色不存在");
			// 删除关联
			var rps = _rpRepo.GetAll().Where(x => ((RolePermission)x).RoleId == request.RoleId).Select(x => (RolePermission)x).ToList();
			if (rps.Count > 0) await _rpRepo.DeleteRangeAsync(rps);
			var ers = _erRepo.GetAll().Where(x => ((EmployeeRole)x).RoleId == request.RoleId).Select(x => (EmployeeRole)x).ToList();
			if (ers.Count > 0) await _erRepo.DeleteRangeAsync(ers);
			await _roleRepo.UpdateAsync(role); // 如需物理删除可改用 Remove，这里沿用Update避免扩增接口
			return true;
		}
	}
}
